package com.retail.system.template.storage;

import cn.hutool.core.util.ObjectUtil;
import com.retail.core.entity.enums.DelFlagEnum;
import com.retail.core.entity.enums.StatusFlagEnum;
import com.retail.core.entity.result.Result;
import com.retail.system.entity.po.FilePo;
import com.retail.system.entity.po.StorageConfigPo;
import com.retail.system.entity.request.FileRequest;
import com.retail.system.entity.vo.FileVo;
import com.retail.system.enums.StorageTypeEnums;
import com.retail.system.mapper.FileMapper;
import com.retail.system.mapper.StorageConfigMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author Administrator
 */
@Component
public class StorageFactory {

    private final StorageConfigMapper storageConfigMapper;

    private final LocalTemplate localTemplate;

    private final OssTemplate ossTemplate;

    private final FileMapper fileMapper;

    public StorageFactory(StorageConfigMapper storageConfigMapper, LocalTemplate localTemplate, OssTemplate ossTemplate, FileMapper fileMapper) {
        this.storageConfigMapper = storageConfigMapper;
        this.localTemplate = localTemplate;
        this.ossTemplate = ossTemplate;
        this.fileMapper = fileMapper;
    }

    public Result saveFile(MultipartFile[] files) {
        if (ObjectUtil.isEmpty(files) && files.length == 0) {
            return Result.fail("没有发现文件，不需要保存文件！");
        }

        Integer useStatusFlag = 1;
        StorageConfigPo useConfig = storageConfigMapper.getConfigByStatusFlag(useStatusFlag);
        if (ObjectUtil.isEmpty(useConfig)) {
            return Result.fail("没有启动存储配置，不能上传文件！");
        }

        try {
            FilePo filePo = null;
            FileVo fileVo = new FileVo();
            if (ObjectUtil.equal(useConfig.getStorageType(), StorageTypeEnums.STORAGE_LOCALE.getValue())) {
                filePo = localTemplate.upload(useConfig, files[0]);
            } else  if (ObjectUtil.equal(useConfig.getStorageType(), StorageTypeEnums.STORAGE_ALI.getValue())) {
                filePo = ossTemplate.upload(useConfig, files[0]);
            }
            filePo.setDelFlag(DelFlagEnum.NO.getValue());
            filePo.setStatusFlag(StatusFlagEnum.USE.getValue());
            FileRequest fileRequest = new FileRequest();
            BeanUtils.copyProperties(filePo, fileRequest);
            fileMapper.save(fileRequest);

            BeanUtils.copyProperties(filePo, fileVo);
            fileVo.setLocation(fileVo.getUrl());

            return Result.success(fileVo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.success();
    }
}
